package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import com.ithema.service.OrderSettingService;
import com.sun.xml.internal.xsom.impl.scd.Iterators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    public void upload(List<OrderSetting> list) {

        //先判断集合是否为空.
        if (list.size() > 0 && list != null) {
            //不为空就遍历
            for (OrderSetting orderSetting : list) {
                try {
                    //判断当前日期是否进行了预约设置
                    long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

                    if (countByOrderDate > 0) {
                        //已经进行了预约设置.执行更新设置
                        orderSettingDao.editNumberByOrderDate(orderSetting);
                    } else {
                        //没有,直接插入
                        orderSettingDao.upload(orderSetting);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {

         String  begin=date + "-1"; //样式2020-8-12
         String   end= date+"-31";
        HashMap<String, String> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        //调用dao,根据日期范围查询预约设置数据
        List<OrderSetting>  list = orderSettingDao.getOrderSettingByMonth(map);
         List<Map> result = new ArrayList<>();
        if (list !=null && list.size()>0){
            for (OrderSetting orderSetting : list) {
                Map<String, Object> map1=new HashMap<>();
                map1.put("date",orderSetting.getOrderDate().getDate()); //获取日期数字
                map1.put("number", orderSetting.getNumber());  //获取预约人数
                map1.put("reservations",orderSetting.getReservations()); //已预约人数
                result.add(map1);
            }

        }

        return result;
    }

    //根据日期设置预约人数
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //先根据日期查询有没有预约设置.有的话就更新.没有的话就插入
       //获取当前日期
        Date orderDate = orderSetting.getOrderDate();
        //查找当前日期有没有预约
        long countByOrderDate = orderSettingDao.findCountByOrderDate(orderDate);
        if (countByOrderDate > 0) {
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
                //如果没有就插入设置的数据
            orderSettingDao.upload(orderSetting);

        }

    }
}




